<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard;

use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use Hyperf\DbConnection\Db;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 跟进任务列表.
 * @Controller
 */
class ClientTasks extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     *
     * @RequestMapping(path="/dashboard/client/tasksList", methods="GET")
     */
    public function handle()
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $data = $this->request->all();
        $timeRange=$this->typeEnum($data);
        $list = Db::table('follow_tasks as task')
            ->join('client as client', 'client.id', '=', 'task.client_id')
            ->leftJoin('work_employee as employee','employee.id','=','client.work_employee_id')
            ->leftJoin('work_employee as salesman','salesman.id','=','client.salesman_id')
            ->when(isset($data['name']) && $data['name'] !== '', function ($query) use ($data) {
                $query->where('client.enterprise_name', 'like', '%' . $data['name'] . '%');
            })
            ->when(isset($data['status']) && is_numeric($data['status']), function ($query) use ($data) {
                $query->where('task.status', '=', $data['status']);
            })
            ->when(!empty($timeRange), function ($query) use ($timeRange) {
                $query->where('task.returned_at', '>=', $timeRange['start_time']);
                $query->where('task.returned_at', '<',  $timeRange['end_time']);
            })
            ->when(isset($data['type']) && $data['type']==3, function ($query) {
                $query->where('task.returned_at', '<', date('Y-m-d 00:00:00'));
                $query->orWhere('task.returned_at', '>', date('Y-m-d 00:00:00',strtotime('+2 day')));
            })
            ->when(isset($data['type']) && $data['type']==4, function ($query) use ($data) {
                $query->where('task.returned_at', '<', date('Y-m-d H:i:s'));
                $query->where('task.status', '=', 0);
            })
            ->orderBy('task.returned_at', 'asc')
            ->orderBy('task.status', 'asc')
            ->select([
                'task.id',
                'client.enterprise_name',
                'client.b2b_user_type',
                'client.province',
                'client.city',
                'client.district',
                'employee.name as employee_name',
                'salesman.name as salesman_name',
                'client.level',
                'task.returned_at',
                'task.status',
                'task.returned_way',
                'client.id as client_id',
            ])->paginate();
        if (!empty($list->items())) {
            foreach ($list->items() as &$datum) {
                $province = Db::table('district')->where('id', $datum->province)->value('name');
                $city = Db::table('district')->where('id', $datum->city)->value('name');
                $district = Db::table('district')->where('id', $datum->district)->value('name');
                $datum->address = $province . $city . $district;
                $datum->status_string="未跟进";
                if ($datum->status==1){
                    $datum->status_string="已完成";
                }
                $datum->returned_way_string='';
                if ($datum->returned_way==1){
                    $datum->returned_way_string='电话';
                }
                if ($datum->returned_way==2){
                    $datum->returned_way_string='面访';
                }
                if ($datum->returned_way==3){
                    $datum->returned_way_string='企业微信';
                }

                $datum->b2b_user_type_string='';
                if ($datum->b2b_user_type==1){
                    $datum->b2b_user_type_string='药店';
                }
                if ($datum->b2b_user_type==2){
                    $datum->b2b_user_type_string='诊所';
                }
                if ($datum->b2b_user_type==3){
                    $datum->b2b_user_type_string='连锁';
                }
                if ($datum->b2b_user_type==4){
                    $datum->b2b_user_type_string='商业';
                }
                unset($datum->province, $datum->city, $datum->district);
            }
            unset($datum);
        }
        return $list;
    }
    private function typeEnum($data)
    {
        $timeRange=[];
        //今日
        if ($data['type'] == 1) {
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00'),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        //明日
        if ($data['type'] == 2) {
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00', strtotime('+1 day')),
                'end_time' => date('Y-m-d 00:00:00',strtotime('+2 day')),
            ];
        }
        return $timeRange;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'status' => 'integer',
            'page' => 'integer',
            'perPage' => 'integer',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'status.integer' => '成员状态必须为整数',
            'page.integer' => '页码必须为整数',
            'perPage.integer' => '页码必须为整数',
        ];
    }
}
